import React, { useContext } from 'react'
import './index.scss'
import { Context } from '../../App'

export default function MyCount({ count, id }) {
  const { changeCount } = useContext(Context)

  const sub = () => {
    let num = count - 1
    if (num < 1) {
      num = 1
    }
    changeCount(id, num)
  }

  const add = () => {
    changeCount(id, count + 1)
  }

  const change = (e) => {
    //! 直接获取的数字是字符串  需要转换成数字
    console.log(+e.target.value, '获取input的值')
    let num = +e.target.value
    if (num < 1) num = 1
    changeCount(id, num)
  }
  return (
    <div className="my-counter">
      <button type="button" className="btn btn-light" onClick={sub}>
        -
      </button>
      <input
        type="number"
        className="form-control inp"
        value={count}
        onChange={change}
      />
      <button type="button" className="btn btn-light" onClick={add}>
        +
      </button>
    </div>
  )
}
